﻿using System;
using System.Linq;
using System.Collections;
using Microsoft.Practices.ServiceLocation;
using System.Windows.Forms;
using LinqKit;
using Syncfusion.Windows.Forms;
using Syncfusion.Windows.Forms.Grid.Grouping;

using PMngr.Data;

namespace PMngr.Main
{
    public partial class ChooseUnit : Office2007Form
    {
        private IRepositoryFactory repositoryFactory;

        public UnitModel SelectedUnit { get; set; }

        public ChooseUnit(IRepositoryFactory repositoryFactory)
        {
            InitializeComponent();            
            // get the system IRepository
            this.repositoryFactory = repositoryFactory;           
            // GridGroupingControl
            InitializeUintGrid();
            InitializeSubsidiaryGrid();

            InitializeControls();
        }

        private void InitializeControls()
        {           
            comUnitType.SelectedIndexChanged -= ComUnitTypeSelectedIndexChanged;
            // 单位区域
            InitializeDropDownList();
            comUnitType.SelectedIndexChanged += ComUnitTypeSelectedIndexChanged; 

            ComUnitTypeSelectedIndexChanged(this, EventArgs.Empty);
        }

        private void InitializeDropDownList()
        {
            using (var repository = repositoryFactory.CreateRepository())
            {
                // 单位区域
                var options1 = repository.All<ItemBase>();
                var datasource1 = from o in options1
                                  where o.Type == "UnitType" && o.IsValid
                                  orderby o.Order
                                  select new {o.Code, o.Name};
                var result1 = datasource1.ToList();
                result1.Insert(0, new {Code = DefaultAll.DefaultValue, Name = DefaultAll.DefaultName});
                comUnitType.DataSource = result1;
                comUnitType.DisplayMember = ItemModel.GetPropertyName(u => u.Name);
                comUnitType.ValueMember = ItemModel.GetPropertyName(u => u.Code);
            }
        }      

        private void ComUnitTypeSelectedIndexChanged(object sender, EventArgs e)
        {
            var unitType = (int)comUnitType.SelectedValue;
            ResetGrid(unitType);
        }
      
        private void ResetGrid(int unitType)
        {
            var predicate = PredicateBuilder.True<Unit>();
            predicate = predicate.And(u => u.IsValid && u.ParentUnit == null);

            using (var repository = repositoryFactory.CreateRepository())
            {
                if (unitType != -1)
                    predicate = predicate.And(u => u.UnitType.Code == unitType);

                var datasource = repository.Find(predicate.Expand());
                var query = from u in datasource
                            select new UnitModel
                                       {
                                           Id = u.Id,
                                           Name = u.Name,
                                           Subsidiary = u.ChildUnits.Where(i => i.IsValid).Count(),
                                           UnitTypeCode = u.UnitType.Code,
                                           UnitType = u.UnitType.Name
                                       };

                var result = query.ToList();

                gridUnits.DataSource = result;
            }

            bindingSource.DataSource = null;
        }

        private void InitializeUintGrid()
        {
            var gcd1 = new GridColumnDescriptor(UnitModel.GetPropertyName(u => u.Name), UnitModel.GetPropertyName(u => u.Name), UnitModel.Dict[UnitModel.GetPropertyName(u => u.Name)], true, 200);
            gridUnits.TableDescriptor.Columns.Add(gcd1);
            var gcd2 = new GridColumnDescriptor(UnitModel.GetPropertyName(u => u.Subsidiary), UnitModel.GetPropertyName(u => u.Subsidiary), UnitModel.Dict[UnitModel.GetPropertyName(u => u.Subsidiary)], true, 80);
            gridUnits.TableDescriptor.Columns.Add(gcd2);
            var gcd3 = new GridColumnDescriptor(UnitModel.GetPropertyName(u => u.UnitType), UnitModel.GetPropertyName(u => u.UnitType), UnitModel.Dict[UnitModel.GetPropertyName(u => u.UnitType)], true, 80);
            gridUnits.TableDescriptor.Columns.Add(gcd3);

            gridUnits.DataSource = null;
            gridUnits.InitializeGridGroupingWithFilter();

            gridUnits.TableControlCellDoubleClick += GridUnitsTableControlCellDoubleClick;
        }     

        private void InitializeSubsidiaryGrid()
        {
            var gcd1 = new GridColumnDescriptor(UnitModel.GetPropertyName(u => u.Name), UnitModel.GetPropertyName(u => u.Name), UnitModel.Dict[UnitModel.GetPropertyName(u => u.Name)], true, 200);
            gridSubsidiaries.TableDescriptor.Columns.Add(gcd1);
            var gcd3 = new GridColumnDescriptor(UnitModel.GetPropertyName(u => u.Capacity), UnitModel.GetPropertyName(u => u.Capacity), UnitModel.Dict[UnitModel.GetPropertyName(u => u.Capacity)], true, 75);
            gridSubsidiaries.TableDescriptor.Columns.Add(gcd3);
            var gcd2 = new GridColumnDescriptor(UnitModel.GetPropertyName(u => u.UnitKind), UnitModel.GetPropertyName(u => u.UnitKind), UnitModel.Dict[UnitModel.GetPropertyName(u => u.UnitKind)], true, 80);
            gridSubsidiaries.TableDescriptor.Columns.Add(gcd2);
            
            gridSubsidiaries.DataSource = bindingSource;
            gridSubsidiaries.InitializeGridGroupingWithFilter();

            gridSubsidiaries.TableControlCellDoubleClick += GridListTableControlCellDoubleClick;
        }

        private void GridListTableControlCellDoubleClick(object sender, GridTableControlCellClickEventArgs e)
        {
            var selecteds = gridSubsidiaries.Table.SelectedRecords;

            if (selecteds != null && selecteds.Count > 0)
            {
                // get the Unit Id
                var selected = selecteds[0].Record;
                SelectedUnit = selected.GetData() as UnitModel;

                DialogResult = DialogResult.OK;
            }   
        }

        private void GridUnitsTableControlCellDoubleClick(object sender, GridTableControlCellClickEventArgs e)
        {
            var selecteds = gridUnits.Table.SelectedRecords;

            if (selecteds != null && selecteds.Count > 0)
            {
                // get the Unit Id
                var selected = selecteds[0].Record;
                var pId = selected.GetValue(UnitModel.GetPropertyName(u => u.Id));
                bindingSource.DataSource = GetSubsidiaries((int)pId);
            }
        }

        private IEnumerable GetSubsidiaries(int pId)
        {
            using (var repository = repositoryFactory.CreateRepository())
            {
                var datasource = repository.Find<Unit>(u => u.IsValid && u.ParentUnit.Id == pId)
                    .Select(u => new UnitModel
                                     {
                                         Id = u.Id,
                                         Name = u.Name,
                                         Capacity = u.Capacity,
                                         IsValid = u.IsValid,
                                         SuperUnit = u.ParentUnit.Name,
                                         UnitType = u.ParentUnit.UnitType.Name,
                                         UnitTypeCode = u.UnitType.Code,
                                         UnitKind = u.UnitType.Name
                                     });

                return datasource.ToList();
            }
        }         
    }   
}
